package pt.isel.pdm.ouryamba;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;

/**
 * Notify all the waiters for network connectivity.
 * */
public class NetworkReceiver extends BroadcastReceiver
{

	private boolean wasOn = false;
	

//BroadcastReceiver methods
	
	/**
	 * Delegate the actions to take when the connectivity has changed.</br>
	 * 
	 * If the connectivity was switched from off to on, then notify all waiters in the variable 
	 * {@code waiterForNetworkLock} of the General class.
	 * */
	@Override
	public void onReceive(Context context, Intent intent) 
	{
		boolean conn = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
		General app = (General) context.getApplicationContext();
		app.log("NetworkReceiver.onReceive(): Network connectivity is " + (conn ? "on." : "off."));
		if(conn && !wasOn)
		{
			app.log("NetworkReceiver.onReceive(): Notify all waiters.");
			wasOn = true;
			synchronized (app.waiterForNetworkLock) 
			{
				app.waiterForNetworkLock.notifyAll();
			}
		}
		else if(!conn && wasOn)
		{
			wasOn = false;
		}	
	}
	
}
